package com.shop.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.SessionFactoryImpl;

import com.shop.event.MyInterceptor;
import com.shop.event.MyLoadListener;
import com.shop.event.MySaveListener;

@SuppressWarnings("unchecked")
public class HibernateUtil {
	private static  Session session;
	private static SessionFactory sessionFactory;
	static{
		StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
				.configure() // configures settings from hibernate.cfg.xml
				.build();
		Configuration config = new Configuration().setInterceptor(new MyInterceptor());
		sessionFactory = config.buildSessionFactory(registry);
		//注册事件监听器
		EventListenerRegistry eventService = ((SessionFactoryImpl)sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
		//使用用户指定的监听器代替系统默认的监听器
		eventService.setListeners(EventType.SAVE, MySaveListener.class);
		eventService.setListeners(EventType.LOAD, MyLoadListener.class);
		
	}
	public static Session getSesssion(){
		session = sessionFactory.openSession();	
		return session;
	}
	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}
	
	public static void closeSession(Session session){
		if(session!=null){
			session.close();
		}
		if(sessionFactory!=null){
			sessionFactory.close();
		}
	}
	
}
